package org.skydiveapphd;

import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapplibrary.R;
import org.skydiveapphd.interfaces.LocationNotifier;
import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.ui.LocationSelectListAdapter;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class LocationSelectListActivity extends BaseListFragment
{	
	public static LocationSelectListActivity newInstance(Bundle args) 
	{
		LocationSelectListActivity f = new LocationSelectListActivity();
		f.setArguments(args);
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{ 
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();

		// init view
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		setHeaderText(R.string.select_location_label);
		
		loadData();
		
		setBottomButtonVisibility(View.GONE);
	}
	
	@Override
	protected void onTopButtonClick()
	{
		FragmentHelper.getInstance().openFragment(LocationEditActivity.newInstance(new Bundle()), android.R.id.tabhost, 
				Constants.TAG_LOCATION_EDIT, getFragmentManager());
	}
	
	@Override
	public void onListItemClick(ListView listView, View view, int indx, long id)
	{
		// get current selection
    	int previousSelectedId = getArguments().getInt(Constants.EXTRA_LOCATION_ID, -1);
    	int newSelectedId = (int)id;
    	  	
		LocationNotifier f = (LocationNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		
    	// if different than previous
		if (previousSelectedId != newSelectedId)
			f.updateLocation(newSelectedId);
		
		getFragmentManager().popBackStack();
	}
	
	private void loadData()
	{
		// populate
		LocationRepository repository = new LocationRepository(getActivity());
		LocationSelectListAdapter adapter = new LocationSelectListAdapter(
				getActivity(),
				repository.getLocations());
		setListAdapter(adapter);
		
		// set initial selection
		int selectedId = getArguments().getInt(Constants.EXTRA_LOCATION_ID, -1);
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					adapter.getItems().get(index).getId() == selectedId); 
		}
	}
} 